package learn_0403; /**
 * @author haomin
 * @date 2022/04/03 18:49
 **/

import java.sql.*;
import java.util.Scanner;

public class Demo1 {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);

        try(Connection c = DBUtil.connection()){

            // 1.增
            String sql1 = "insert into readers (name) values (?)";
            String newReaderName = scanner.next();
            //Statement.RETURN_GENERATED_KEYS 得到自增值操作
            try(PreparedStatement ps = c.prepareStatement(sql1,Statement.RETURN_GENERATED_KEYS)){
                ps.setString(1,newReaderName);
                ps.executeUpdate();
                try(ResultSet rs = ps.getGeneratedKeys()){
                    rs.next();
                    int rid = rs.getInt(1);
                    System.out.println("新插入了一个reader:" + rid +"\t"+newReaderName);
                }
            }

            // 2.删
            String sql2 = "delete from readers where name = '刘昕怡'";
            try(PreparedStatement ps = c.prepareStatement(sql2)){
                ps.executeUpdate();
            }

            // 3.改
            String sql3 = "update readers set name = '刘昕怡' where name = '陈浩民'";
            try (PreparedStatement ps = c.prepareStatement(sql3)){
                ps.executeUpdate();
            }

            // 4.查
            String sql4 = "select * from books where 1 = 1";
            try(PreparedStatement ps = c.prepareStatement(sql4)){
                try(ResultSet rs = ps.executeQuery()){
                    while (rs.next()){
                        int rid = rs.getInt(1);
                        String name = rs.getString(2);
                        int stock = rs.getInt(3);
                        int total = rs.getInt(4);
                        System.out.printf("%d\t%s\t%d\t%d\n",rid,name,stock,total);
                    }
                }
            }
        }
    }
}
